<template>
  <el-drawer :visible.sync="drawer" direction="rtl" size="50%" :with-header="false" :width="700">
    <div class="drawer_box">
      <div class="drawer_title">
        <div class="drawer_t">
          <div class="drawer_t_l">
            <img class="drawer_t_l_img" src="/static/skin/herodoo/main/platform/home/img/piliangoumai.png" alt="" />
            {{ isEdit == 'CREATE' ? ' 新建投票' : '编辑投票' }}
          </div>
          <img class="drawer_t_r" src="/static/skin/herodoo/main/platform/home/img/guanbi.png" alt=""
            @click="drawer = false" />
        </div>
      </div>
      <div class="drawer_content">
        <text>基本信息</text>
        <div class="list-box">
          <div class="left">投票标题:</div>
          <div class="right">
            <el-input v-model="form.headline"></el-input>
          </div>
        </div>
        <div class="list-box">
          <div class="left">投票时间:</div>
          <div class="right">
            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="cutOffTiem" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </div>
        </div>
        <div class="list-box">
          <div class="left">图片:</div>
          <div class="right">
            <div class="tips">
              附图可上传1张图片，图片不超过512KB，仅支持jpg、png格式
            </div>
            <imgUplode :list="form.fileList" @imgList="getImgsUrl" :octopus="octopus" :min="1">
            </imgUplode>
          </div>
        </div>
        <div class="list-box">
          <div class="left">投票说明:</div>
          <div class="right">
          </div>
        </div>
        <div class="desc">
          <quill ref="quill" :octopus="octopus" @quillContent="getQuillContent" :desc="form.deltedContent"
            :isEdit="!['CREATE', 'UPDATE'].includes(isEdit)" :key="getQuillContent"></quill>
        </div>
        <div class="list-box">
          <div class="left">选项类型:</div>
          <div class="right" style="width: 90%;">
            <el-select v-model="value" placeholder="请选择">
              <el-option v-for="item in Select" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <div class="optionBox">
              <div class="optionList" v-for="(item, index) in SelectArr" :key="item.id">
                <div style="width: 10%;">
                  <div> 序号:{{ index + 1 }}</div>
                  <div v-if="SelectArr.length > 1" @click="deleteRefund(index)"><i class="el-icon-delete"></i> 删除</div>
                </div>
                <div style="width: 90%;">
                  <el-input placeholder="请输入选项名称" v-model="item.name" clearable>
                  </el-input>
                  <el-input style="margin: 20px 0;" type="textarea" placeholder="请输入描述内容" v-model="item.textarea"
                    maxlength="150" show-word-limit>
                  </el-input>
                  <div>
                    <div style="display: flex;" v-if="value == 2">
                      <div style="margin-right: 10px;">图片上传:</div>
                      <imgUplode :list="item.Image" @imgList="getSelectArr($event, index, 'Image')" :octopus="octopus"
                        :min="1">
                      </imgUplode>
                      <div style="margin-left: 10px;">格式要求（jpg,jpeg,png,gif,svg）</div>
                    </div>
                    <div style="display: flex;" v-if="value == 4">
                      <div style="margin-right: 10px;">视频上传:</div>
                      <FileUpdate size=102400 DefaultType=".mp4" :list="item.video"
                        @FileList="getSelectArr($event, index, 'video')" :octopus="octopus" :min="1">
                      </FileUpdate>
                      <div style="margin-left: 10px;">格式要求:mp4,文件大小:100M</div>
                    </div>
                    <div style="display: flex;" v-if="value == 3">
                      <div style="margin-right: 10px;">音频上传:</div>
                      <FileUpdate size=10240 DefaultType=".mp3" :list="item.audio"
                        @FileList="getSelectArr($event, index, 'audio')" :octopus="octopus" :min="1">
                      </FileUpdate>
                      <div style="margin-left: 10px;">格式要求:mp3,文件大小:10M</div>
                    </div>
                  </div>
                </div>

              </div>

            </div>
            <div @click="addSelect()"><i class="el-icon-plus"></i>新增投票选项</div>
          </div>
        </div>
        <div class="list-box">
          <div class="left">是否允许多选:</div>
          <div class="right">
            <el-radio disabled v-model="multipleChoice" label="1">是</el-radio>
            <el-radio disabled v-model="multipleChoice" label="0">否</el-radio>
          </div>
        </div>
        <div class="list-box">
          <div class="left">展示类型:</div>
          <div class="right">
            <el-radio v-model="resultsDisplay" label="1">投票前显示</el-radio>
            <el-radio v-model="resultsDisplay" label="2">投票后显示</el-radio>
            <el-radio v-model="resultsDisplay" label="3">始终不显示</el-radio>
          </div>
        </div>
        <div class="list-box">
          <div class="left">是否置顶:</div>
          <div class="right">
            <el-radio v-model="topPost" label="1">是</el-radio>
            <el-radio v-model="topPost" label="0">否</el-radio>
          </div>
        </div>
        <!-- <div class="list-box">
          <div class="left">是否发布:</div>
          <div class="right">
            <el-radio v-model="publishStatus" label="1">是</el-radio>
            <el-radio v-model="publishStatus" label="0">否</el-radio>
          </div>
        </div> -->
      </div>

      <div class="button_list" v-if="isEdit != 'look'">
        <button style="background-color: #1E1B19;" @click="save(0)"> 暂存 </button>
        <button @click="save(1)">发布</button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import imgUplode from "@/components/Components/imgUpdate.vue";
import quill from "@/components/Components/quillEditor.vue";
import FileUpdate from "../../Components/FileUpdate.vue";
export default {
  components: {
    quill,
    FileUpdate,
    imgUplode
  },
  name: "cat_dialog",
  props: {
    isEdit: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      cutOffTiem: [],
      multipleChoice: '0',
      resultsDisplay: '2',
      topPost: '0',
      publishStatus: '0',
      octopus: this.$parent.octopus,
      drawer: false,
      isEdit: 'CREATE',
      form: {
        ID: 1,
        StartTime: '',
        EndTime: '',
        fileList: [],
        headline: '',
        deltedContent: "",
      },
      value: '1',
      Select: [{
        value: '1',
        label: '文本'
      }, {
        value: '2',
        label: '文本+图片'
      }, {
        value: '3',
        label: '文本+音频'
      }, {
        value: '4',
        label: '文本+视频'
      }],
      SelectArr: [
        {
          id: 1,
          name: '',
          Image: [],
          video: [],
          audio: [],
          textarea: '',
          Attachment: []
        },
      ],
      storage: []
    };
  },
  created() { },
  watch: {
    cutOffTiem(newValue) {
      this.form.StartTime = newValue[0]
      this.form.EndTime = newValue[1]
    }
  },
  activated() {
  },
  methods: {
    deleteRefund(index) {
      this.SelectArr.splice(index, 1);
    },
    addSelect() {
      let ArrLength = Math.floor(Math.random() * 90000) + 10000
      const newRefundType = {
        id: ArrLength,
        name: '',
        Image: [],
        video: [],
        audio: [],
        textarea: '',
        Attachment: []
      }
      // 将新对象添加到数组中
      this.SelectArr.push(newRefundType);
    },
    // FileListEv(){
    //   this.$set(this.SelectArr[index].fileList, 0, fileList[0]);
    // },
    getSelectArr(fileList, index, type) {
      if (fileList.length == 0) {
        this.$set(this.SelectArr[index], type, [])
      } else {
        this.$set(this.SelectArr[index][type], 0, fileList[0]);
      }

    },
    getImgsUrl(fileList) {
      this.form.fileList = fileList
      // this.$set(this.form.fileList, 0, fileList[0]);
    },
    getQuillContent(e) {
      this.form.deltedContent = e;
    },
    drawerOpen(data = null, type = 'CREATE') {
      // editType 是否可编辑，打他 父级传的数据，type  是新建还是更新
      this.multipleChoice = '0'
      this.resultsDisplay = '2'
      this.topPost = '0'
      this.publishStatus = '0'
      this.drawer = true;
      this.isEdit = type;
      if (this.isEdit == 'CREATE') {
        this.cutOffTiem = []
        this.form = {
          ID: 1,
          StartTime: '',
          EndTime: '',
          fileList: [],
          headline: '',
          deltedContent: "",
        }
        this.SelectArr = [
          {
            id: 1,
            name: '',
            Image: [],
            video: [],
            audio: [],
            textarea: '',
            Attachment: []
          },
        ]

      }
      if (this.isEdit == 'UPDATE') {
        this.form.ID = data.ID
        this.form.headline = data.Name
        this.$set(this.cutOffTiem, 0, data.StartTime);
        this.$set(this.cutOffTiem, 1, data.EndTime);
        this.form.fileList = JSON.parse(data.PicturePath)
        this.form.deltedContent = data.Description
        this.value = `${data.VoteOptionTypeID}`
        this.multipleChoice = `${data.IsMultipleChoice}`
        this.resultsDisplay = `${data.VoteTypeID}`
        this.publishStatus = `${data.IsRelease}`
        this.topPost = `${data.IsTop}`
        this.gitDetailedList(data.ID)
      }
    },
    save(status = 1) {

      let isValid = true
      if (!this.form.headline) {
        this.$message.error('请完善标题');
      } else if (!this.form.StartTime && !this.form.EndTime) {
        this.$message.error('请完善投票截止日期');
      } else if (this.form.fileList.length == 0) {
        this.$message.error('请上传投票图片');
      } else if (!this.form.deltedContent) {
        this.$message.error('请完善投票说明');
      } else {
        for (const [index, item] of this.SelectArr.entries()) {
          if (item.name.trim() == '' || item.textarea.trim() == '') {
            isValid = false;
            this.$message.error(`序号 ${index + 1} 的名称或描述不能为空`);
            return;
          } else if (item.Image.length == 0 && this.value == 2) {
            isValid = false;
            this.$message.error(`序号 ${index + 1} 的图片不能为空`);
            return;
          } else if (item.audio.length == 0 && this.value == 3) {
            isValid = false;
            this.$message.error(`序号 ${index + 1} 的音频不能为空`);
            return;
          } else if (item.video.length == 0 && this.value == 4) {
            isValid = false;
            this.$message.error(`序号 ${index + 1} 的视频不能为空`);
            return;
          }
        }
        if (isValid) {
          // console.log(this.SelectArr)
          // return
          this.$confirm(`确定${status ? '发布' : '暂存'}这个广告吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            // type: 'warning'
            center: true
          }).then(res => {
            this.update_api_1345(status)
          }).catch(() => {
            console.log('取消了');
          })

        }

      }
    },
    update_api_1345(status = 1) {
      let this_ = this
      this.octopus.request.api.post(
        "/Octopus/Engine/Item",
        {
          id: 1345,
          type: this_.isEdit,
          value: this.isEdit == 'UPDATE' ? this.form.ID : '',
          cellData: [
            { name: "CreateUserID", defaultValue: this_.octopus.passport.id },	// 创建人
            { name: "Description", defaultValue: this_.form.deltedContent },	// 投票内容
            { name: "EndTime", defaultValue: this_.form.EndTime },	// 结束时间
            { name: "ID" },	// ID
            { name: "IsMultipleChoice", defaultValue: this_.multipleChoice },	// 是否多选（0单选  1多选）
            { name: "VoteTypeID", defaultValue: this_.resultsDisplay },	// 投票是否公开（0不  1是）（用户投票完成是否可以直接看到所选的选项的票数  ）
            { name: "IsTop", defaultValue: this_.topPost },	// 是否置顶
            { name: "IsRelease", defaultValue: status },	// 是否发布(0不  1发布)
            { name: "Name", defaultValue: this_.form.headline },	// 投票标题
            { name: "OptionNumber" },	// 可选数量
            { name: "PicturePath", defaultValue: JSON.stringify(this_.form.fileList) },	// 图片
            { name: "StartTime", defaultValue: this_.form.StartTime },	// 开始时间
            { name: "VoteOptionTypeID", defaultValue: this_.value },	// 投票选项内容（1图文  2音频）
          ],
        },
        (data) => {
          if (data.status.code == 200) {
            let disposeData = this.compareArrays(this.storage, this.SelectArr);
            let queue = []
            disposeData.map(item => {
              queue.push(this_.CRVoteItem(data.content.value, item))
            })
            Promise.all(queue).then(res => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.drawer = false;
              this_.$emit('reload')
            })
          } else {
            this.octopus.tips.error(data);
          }
        });
    },
    CRVoteItem(ID, data) {
      return new Promise((resolve, reject) => {
        if (this.value == 2) {
          data.Attachment = data.Image
        }
        if (this.value == 3) {
          data.Attachment = data.audio
        }
        if (this.value == 4) {
          data.Attachment = data.video
        }
        let this_ = this
        this.octopus.request.api.post(
          "/Octopus/Engine/Item",
          {
            id: 1346,
            type: data.type,
            value: data.type == 'CREATE' ? '' : data.id,
            cellData: [
              { name: "Attachment", defaultValue: JSON.stringify(data.Attachment) },	// 附件（音频、视频）
              { name: "CreateUserID", defaultValue: this_.octopus.passport.id },	// 创建人
              { name: "Description", defaultValue: data.textarea },	// 选项内容（图文描述）
              { name: "Name", defaultValue: data.name },	// 选项名称
              { name: "VoteID", defaultValue: ID },	// 投票表ID
            ],
          },
          (data) => {
            if (data.status.code == 200) {
              resolve(data)
            } else {
              this.octopus.tips.error(data);
              reject(data)
            }
          });
      })
    },
    gitDetailedList(ID) {
      let this_ = this
      this.octopus.request.api.post(
        "/Octopus/Engine/List",
        {
          id: 1346,
          cellData: [
            { name: "Attachment" },	// 附件（音频、视频）
            { name: "CreateTime" },	// 创建时间
            { name: "CreateUserID" },	// 创建人
            { name: "Description" },	// 选项内容（图文描述）
            { name: "ID" },	// ID
            { name: "Name" },	// 选项名称
            { name: "VoteID", filterKey: '=', filterValue: ID },	// 投票表ID
          ],
        },
        (data) => {
          if (data.status.code == 200) {
            this.SelectArr = data.content.queryData.map(item => {
              return {
                id: item.ID,
                name: item.Name, // 如果有名称的字段可以赋值
                Image: this.value == '2' ? JSON.parse(item.Attachment) : [], // 图片等其他属性也可以赋值
                video: this.value == '4' ? JSON.parse(item.Attachment) : [],
                audio: this.value == '3' ? JSON.parse(item.Attachment) : [],
                textarea: item.Description,
                Attachment: JSON.parse(item.Attachment)
              };
            });
            this.storage = JSON.parse(JSON.stringify(this.SelectArr))
          } else {
            this.octopus.tips.error(data);
          }
        });
    },
    compareArrays(A, B) {
      let C = [];

      // 对比 B 数组中的每个对象
      B.forEach(objB => {
        // 在 A 数组中查找是否存在相同 id 的对象
        let foundInA = A.find(objA => objA.id === objB.id);

        if (!foundInA) {
          // 如果在 A 中找不到对应 id 的对象，则为 CREATE
          C.push({ ...objB, type: 'CREATE' });
        } else {
          // 如果在 A 中找到了对应 id 的对象，则为 UPDATE
          C.push({ ...objB, type: 'UPDATE' });
        }
      });

      // 查找在 A 中存在但在 B 中不存在的对象，标记为 DELETE
      A.forEach(objA => {
        let foundInB = B.find(objB => objB.id === objA.id);
        if (!foundInB) {
          C.push({ ...objA, type: 'DELETE' });
        }
      });

      return C;
    }
  },
};
</script>
<style scoped>
.optionList {
  display: flex;
  margin: 20px 0;
}

.drawer_box {
  padding: 3rem 0.8rem 3rem 0;
  height: calc(100% - 5rem);
  display: flex;
  flex-direction: column;
}

.drawer_title {
  box-shadow: 0px 5px 5px rgb(230 228 228 / 30%);
  padding-bottom: 1rem;
  font-size: 1.6rem;
}

.drawer_t {
  padding: 0 2.8rem;
  display: flex;
  justify-content: space-between;
}

.drawer_t_l {
  display: flex;
  align-items: center;
  font-size: 2rem;
  font-weight: bold;
}

.drawer_t_l_img {
  width: 2.8rem;
  margin-right: 1rem;
}

.drawer_t_r {
  width: 3rem;
  height: 3rem;
  cursor: pointer;
}

.button_box {
  margin-top: 1rem;
  padding: 0 3rem;
  display: flex;
}

.drawer_content {
  overflow-y: auto;
  margin-top: 1.5rem;
  height: calc(100vh - 11rem);
  padding: 0 3rem;
  width: 100%;
  padding-bottom: 1rem;
}

.drawer_content .title {
  font-size: 1.8rem;
  font-weight: bold;
}

.drawer_content .driver-title {
  margin-top: 1em;
}

.content-box {
  display: flex;
  align-items: center;
  margin: 2rem 0 2rem 2em;
}

.mt-10 {
  margin-top: 10rem;
}

.content-box .label {
  width: 25%;
  font-size: 1.6rem;
}

.content-box .label .label-bold {
  font-size: 1.8rem;
  font-weight: bold;
}

.content-box .desc {
  flex: 1;
  font-size: 1.6rem;
}

.list-box {
  display: flex;
  width: 100%;
  justify-content: space-between;
}

.list-box {
  line-height: 4rem;
  margin-top: 2rem;
}

.list-box .left {
  width: 20%;
  font-size: 1.5rem;
}

.list-box .right {
  width: 80%;
}

.button_list {
  margin-top: 1rem;
  display: flex;
  justify-content: end;
  position: absolute;
  background-color: #ffff;
  bottom: 1rem;
  width: calc(100% - 7rem);
}

.button_list button {
  border: none;
  height: 4rem;
  width: 12rem;
  border-radius: 1rem;
  margin-left: 1rem;
  color: #ffff;
  background-color: #F78C53;
  cursor: pointer;
}
</style>